package main

import (
	"bufio"
	"context"
	"embed"
	"flag"
	"fmt"
	"io/fs"
	"log"
	"os"
	"path/filepath"
	"strings"
	"time"

	"yx.io/qwq-ai/ai"
	"yx.io/qwq-ai/myComponent"
	"yx.io/qwq-ai/server"
)

//go:embed static
var staticFiles embed.FS

func main() {
	// 初始化日志组件
	myComponent.LogInit()

	addr := flag.String("addr", ":8888", "设置http服务器监听地址, 例如：:8888 将监听所有网卡的tcp 8888端口")
	appId := flag.String("appId", "", "设置qwq-ai的appId，例如：-appId=xxx，支持环境变量DASHSCOPE_APP_ID")
	apiKey := flag.String("apiKey", "", "设置qwq-ai的apiKey，例如：-apiKey=xxx，支持环境变量DASHSCOPE_API_KEY")
	flag.Parse()

	if *appId == "" {
		*appId = os.Getenv("DASHSCOPE_APP_ID")
		if *appId == "" {
			*appId = waitInput("appId", 60)
			if *appId == "" {
				os.Exit(1)
			}
		}
	}
	if *apiKey == "" {
		*apiKey = os.Getenv("DASHSCOPE_API_KEY")
		if *apiKey == "" {
			*apiKey = waitInput("apiKey", 60)
			if *apiKey == "" {
				os.Exit(1)
			}
		}
	}

	ai.AppId = *appId
	ai.ApiKey = *apiKey

	// 释放静态资源
	extractStaticFiles()
	// 启动 HTTP 服务器
	server.StartHttpServer(*addr)

}

var exePath, _ = os.Executable()
var BaseDir = filepath.Dir(exePath)

func extractStaticFiles() {
	fs.WalkDir(staticFiles, ".", func(path string, d fs.DirEntry, err error) error {
		if err != nil {
			return err
		}
		targetPath := filepath.Join(BaseDir, path)
		if d.IsDir() {
			return os.MkdirAll(targetPath, 0755)
		} else {
			// 判断目标文件是否已存在，存在着跳过
			if _, err := os.Stat(targetPath); err == nil {
				return nil
			}
			data, err := staticFiles.ReadFile(path)
			if err != nil {
				log.Printf("读取嵌入文件失败: %v", err)
				return err
			}
			log.Printf("释放文件: %s", targetPath)
			return os.WriteFile(targetPath, data, 0644)
		}
	})
}

// 等待用户输入变量的值，超过给定时间则直接返回空字符串
func waitInput(variableName string, waitSeconds int) string {
	ctx, cancel := context.WithTimeout(context.Background(), time.Duration(waitSeconds)*time.Second)
	defer cancel()

	result := make(chan string, 1)

	go func() {
		reader := bufio.NewReader(os.Stdin)
		log.Printf("请在 %d 秒内输入 %s（直接回车视为无效），超时将自动退出: ", waitSeconds, variableName)
		for {
			in, _ := reader.ReadString('\n')
			in = strings.TrimSpace(in)
			if in != "" {
				result <- in
				return
			}
			// 空输入，继续循环让用户重输
		}
	}()

	select {
	case val := <-result:
		log.Printf("输入的 %s 为: %s", variableName, val)
		return val
	case <-ctx.Done():
		fmt.Println()
		log.Printf("等待 %s 超时", variableName)
		return ""
	}
}
